use simple_redis::{network, Backend};
use tracing::{info, level_filters::LevelFilter};
use tracing_subscriber::{fmt::Layer,layer::SubscriberExt,util::SubscriberInitExt,Layer as _};
use anyhow::Result;


#[tokio::main]
async fn main() -> Result<()> {
    let layer = Layer::new().with_filter(LevelFilter::INFO);
    tracing_subscriber::registry().with(layer).init();
    info!("Starting the server...");
    let addr = "0.0.0.0:6379";
    info!("simple-redis is listening on {}", addr);
    let listener = tokio::net::TcpListener::bind(addr).await?;
    let backend = Backend::new();
    loop {
        let (stream, raddr) = listener.accept().await?;
        info!("Accepted connection from {}", raddr);
        let clone_backend = backend.clone();
        tokio::spawn(async move {
            if let Err(e) = network::stream_handler(stream, clone_backend).await {
                info!("Error handling connection from  {:?}, error: {:?}", raddr, e);
            }
        });
    }
}